package com.hua.yuan.util;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.target.Target;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;

/**
 * 时间：2018/8/30
 * 作者：蓝天
 * 描述：
 */
public class GlideLoadUtil {

    private static String url = "http://qq.yh31.com/tp/zjbq/201612231514480890.gif";
    /**
     * 对保存的图片命名
     */
    private String imagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + System.currentTimeMillis() +".jpg";

    public void loadPic(final Context context) {
        //String path =   getImagePath(url);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String path = getImagePath(context, url);
                /**
                 * 拷贝到指定路径
                 */
                copyFile(path, imagePath);
                Intent intentBroadcast = new Intent(
                        Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                File file = new File(imagePath);
                intentBroadcast.setData(Uri.fromFile(file));
                context.sendBroadcast(intentBroadcast);
                ToastUtil.showLongToast( "下载成功");
            }
        }).start();
    }


    /**
     * Glide 获得图片缓存路径
     */
    private String getImagePath(Context context, String imgUrl) {
        String path = null;
        FutureTarget<File> future = Glide.with(context)
                .load(imgUrl)
                .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
        try {
            File cacheFile = future.get();
            path = cacheFile.getAbsolutePath();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return path;
    }

    public void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();

        }

    }


}
